package com.reef.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.reef.dao.BookborrewviewRepository;
import com.reef.dto.bbviewDto;
import com.reef.entity.Bookborrew_view;
import com.reef.service.BookborrewviewService;
@Service
public class BookborrewviewServiceImpl implements BookborrewviewService{
	@Autowired
	private BookborrewviewRepository bkvRepository;
	
	public Page<Bookborrew_view> findByCondition(bbviewDto bbDto, Pageable pageable) {
		Specification<Bookborrew_view> viewSpec = viewGetSpec(bbDto); 
		return bkvRepository.findAll(viewSpec, pageable);
	}
	public Specification<Bookborrew_view> viewGetSpec(final bbviewDto bbDto) {
		return new Specification<Bookborrew_view>() {

			public Predicate toPredicate(Root<Bookborrew_view> root, CriteriaQuery<?> query,
					CriteriaBuilder criteriaBuilder) {
				Predicate p=criteriaBuilder.conjunction();
				List<Expression<Boolean>> list =p.getExpressions();
				if(bbDto.getName()!=null && bbDto.getName()!="") {
					list.add(criteriaBuilder.like(root.get("name").as(String.class), "%"+bbDto.getName()+"%"));
				}
				if(bbDto.getAuthor()!=null && bbDto.getAuthor()!="") {
					list.add(criteriaBuilder.like(root.get("author").as(String.class), "%"+bbDto.getAuthor()+"%"));
				}
				if(bbDto.getMaxprice()!=null && bbDto.getMaxprice()!="") {
					list.add(criteriaBuilder.lessThanOrEqualTo(root.get("price").as(String.class), bbDto.getMinprice()));
				}
				if (bbDto.getMinprice()!=null && bbDto.getMinprice()!="") {
					list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("price").as(String.class), bbDto.getMinprice()));
				}
				if (bbDto.getLanguage()!=null && bbDto.getLanguage()!="") {
					list.add(criteriaBuilder.equal(root.get("language").as(String.class),bbDto.getLanguage() ));
				}
				if (bbDto.getClass_name()!=null && bbDto.getClass_name()!="") {
					list.add(criteriaBuilder.equal(root.get("class_name").as(String.class),bbDto.getClass_name() ));
				}
				if (bbDto.getIsbn()!=null && bbDto.getIsbn()!="") {
					list.add(criteriaBuilder.equal(root.get("isbn").as(String.class),bbDto.getIsbn() ));
				}
				return p;
			}
		};
		
	}
	public List<String> selClassName() {
		// TODO Auto-generated method stub
		return bkvRepository.selClassName();
	}

}
